package cn.tedu.knows.portal.service.impl;

import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.mapper.QuestionTagMapper;
import cn.tedu.knows.portal.mapper.UserMapper;
import cn.tedu.knows.portal.mapper.UserQuestionMapper;
import cn.tedu.knows.portal.model.*;
import cn.tedu.knows.portal.mapper.QuestionMapper;
import cn.tedu.knows.portal.service.IQuestionService;
import cn.tedu.knows.portal.service.ITagService;
import cn.tedu.knows.portal.service.IUserService;
import cn.tedu.knows.portal.vo.QuestionVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2021-11-26
 */
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public PageInfo<Question> getMyQuestion(String username,Integer pageNum,Integer pageSize) {
        //先根据用户名查询用户对象
        User user = userMapper.findUserByUsername(username);
        //QueryWrapper类定义查询条件
        QueryWrapper<Question> query = new QueryWrapper<>();
        query.eq("user_id", user.getId());
        query.eq("delete_status", 0);
        query.orderByDesc("createtime");
        PageHelper.startPage(pageNum, pageSize);
        List<Question> list = questionMapper.selectList(query);
        //返回之前将list中所有问题对象的tags属性赋值
        for (Question q : list) {
            List<Tag> tags = tagNameToTags(q.getTagNames());
            q.setTags(tags);
        }
        //修改分页查询的返回值
        return new PageInfo<>(list);
    }

    @Autowired
    private ITagService tagService;

    private List<Tag> tagNameToTags(String tagNames) {
        String[] names = tagNames.split(",");
        Map<String, Tag> tagMap = tagService.getTagMap();
        List<Tag> tags = new ArrayList<>();
        for (String name : names) {
            Tag t = tagMap.get(name);
            tags.add(t);
        }
        return tags;
    }

    @Autowired
    private IUserService userService;
    @Autowired
    private QuestionTagMapper questionTagMapper;
    @Autowired
    private UserQuestionMapper userQuestionMapper;

    @Override
    @Transactional
    public void saveQuestion(QuestionVO questionVO, String username) {
        // 1.根据用户名查询用户对象
        User user = userMapper.findUserByUsername(username);
        // 2.将用户选中的所有标签拼接为一个字符串
        StringBuilder builder = new StringBuilder();
        for (String tagName : questionVO.getTagNames()) {
            builder.append(tagName).append(",");
        }
        String tagNames=builder.deleteCharAt(builder.length()-1).toString();
        // 3.实例化Question对象,收集所有数据库中的信息
        Question question = new Question()
                .setTitle(questionVO.getTitle())
                .setContent(questionVO.getContent())
                .setUserNickName(user.getNickname())
                .setUserId(user.getId())
                .setCreatetime(LocalDateTime.now())
                .setStatus(0)
                .setPageViews(0)
                .setPublicStatus(0)
                .setDeleteStatus(0)
                .setTagNames(tagNames);
        // 4.执行新增Question
        int num = questionMapper.insert(question);
        if (num != 1) {
            throw new SecurityException("数据库忙");
        }
        String s=null;
        s.lastIndexOf("1");
        // 5.新增问题和标签的关系
        // 因为要获得标签名对应的id,所以先将包含所有标签的Map获取过来
        Map<String,Tag> tagMap=tagService.getTagMap();
        // 遍历当前问题选中的所有标签的数组
        for(String tagName: questionVO.getTagNames()){
            // 根据标签名称获得标签对象
            Tag t=tagMap.get(tagName);
            QuestionTag questionTag=new QuestionTag()
                    .setQuestionId(question.getId())
                    .setTagId(t.getId());
            num=questionTagMapper.insert(questionTag);
            if(num!=1){
                throw new ServiceException("数据库忙");
            }
            log.debug("新增了问题和标签的关系:{}",questionTag);
        }

        // 6.新增问题和讲师的关系
        Map<String, User> userMap = userService.getTeacherMap();
        for (String nickname : questionVO.getTeacherNicknames()) {
            User teacher = userMap.get(nickname);
            UserQuestion userQuestion = new UserQuestion()
                    .setQuestionId(question.getId())
                    .setUserId(teacher.getId())
                    .setCreatetime(LocalDateTime.now());
            num = userQuestionMapper.insert(userQuestion);
            if (num != 1) {
                throw new ServiceException("数据库忙");
            }
            log.debug("新增了问题和讲师的关系:{}", userQuestion);

        }
    }

    @Override
    public PageInfo<Question> getTeacherQuestions(String username, Integer pageNum, Integer pageSize) {
        //根据用户名获得用户信息
        User user = userMapper.findUserByUsername(username);
        //设置分页条件
        PageHelper.startPage(pageNum, pageSize);
        //执行查询
        List<Question> list = questionMapper
                .findTeacherQuestions(user.getId());
        //遍历查询结果将每个问题对应的标签赋值
        for (Question q : list) {
            List<Tag> tags = tagNameToTags(q.getTagNames());
            q.setTags(tags);
        }
        //返回任务列表
        return new PageInfo<>(list);
    }

    @Override
    public Question getQuestionById(Integer id) {
        Question question = questionMapper.selectById(id);
        List<Tag> tags = tagNameToTags(question.getTagNames());
        question.setTags(tags);
        return question;
    }

}
